<?php
/**
 * @author all@cosmos-framework.org
 * @copyright (c) 2013 cosmos-framework.org
 * @license http://www.opensource.org/licenses/mit-license.php
 * @link http://cosmos-framework.org/
 * @package cosmos.framework
 * @version 2.0
 */
namespace Cosmos;

class URL {

    /**
     * @uses $_SERVER.REQUEST_METHOD
     */
    public static function handle() {

        preg_match('/^\/([^\/]+?)(?:\/(.*))?$/', self::path(), $p);

        $p[1] = empty($p[1]) ? null : str_replace('.', '\\', $p[1]);
        $p[2] = empty($p[2]) ? null : explode('/', $p[2]);

        try {
            // { component }/{ args }/...
            echo self::_invoke($p[1], $p[2]);
        } catch (\LogicException $e) {
            throw new Exception('Not found.', 404, $e);
        } catch (\ReflectionException $e) {
            throw new Exception('Not allowed.', 405, $e);
        }
    }

    /**
     * @uses $_SERVER.HTTPS
     * @return boolean
     */
    public static function isSSL() {

        return ($_ = &$_SERVER['HTTPS']) ? strcmp($_, 'off') : false;
    }

    /**
     * @uses $_SERVER.REQUEST_URI
     * @return string
     */
    public static function path() {

        return parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
    }

    /**
     * @param string $component
     * @param mixed[] $componentArgs
     * @return mixed
     */
    private static function _invoke($component, $componentArgs) {

        return call_user_func_array(array(new Component($component), $_SERVER['REQUEST_METHOD']), $componentArgs ? : array());
    }

}
